import { Button, Group, PasswordInput, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

export function LoginPage() {
    const navigate = useNavigate();
    const form = useForm({
        initialValues: {
            username: '',
            password: '',
        },
        validate: {
            username: (value) => (value.length < 3 ? '用户名至少3个字符' : null),
            password: (value) => (value.length < 4 ? '密码至少4个字符' : null),
        },
    });

    const handleSubmit = async (values: typeof form.values) => {
        try {
            const response = await axios.post('/app-api/login', values);
            console.log(response);
            if (response && response.data.success) {
                //在localStorage存储用户信息
                localStorage.setItem('user', JSON.stringify(response.data));
                localStorage.setItem('user_role', response.data.role);
                notifications.show({
                    title: '登录成功',
                    message: '欢迎回来',
                    color: 'green',
                });
                navigate('/plant-recognition');
            } else {
                notifications.show({
                    title: '登录失败',
                    message: response.data.error || '服务器错误',
                    color: 'red',
                });
            }
        } catch (err) {
            const error = err as Error & { response?: { data?: { error?: string } } };
            notifications.show({
                title: '登录失败',
                message: error.response?.data?.error || error.message || '服务器错误',
                color: 'red',
            });
        }
    };

    return (
        <div className="min-h-screen bg-gray-100 p-4 flex items-center justify-center">
            <div className="max-w-md w-full p-6 bg-white rounded-lg shadow-md">
                <h2 className="text-2xl font-bold mb-6 text-center">用户登录</h2>
                <form onSubmit={form.onSubmit(handleSubmit)}>
                    <TextInput
                        label="用户名"
                        placeholder="输入用户名"
                        {...form.getInputProps('username')}
                        className="mb-4"
                    />
                    <PasswordInput
                        label="密码"
                        placeholder="输入密码"
                        {...form.getInputProps('password')}
                        className="mb-6"
                    />
                    <Group grow>
                        <Button type="submit">
                            立即登录
                        </Button>
                        <Button variant="light" onClick={() => navigate('/register')}>
                            注册账号
                        </Button>
                    </Group>
                </form>
            </div>
        </div>
    );
}